Java 26-Day Course - Day 5: Loops

Day 5: Loops

Loops are used to execute the same code multiple times. Java provides three types of loops: for, while, and do-while. Use for when the number of iterations is known, and while when repeating based on a condition.

for Loop

The most commonly used loop when the number of iterations is clear.

public class ForLoopExample {
    public static void main(String[] args) {
        // Basic for loop: print 1 to 10
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        // Reverse iteration
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        System.out.println();

        // Increment by 2
        for (int i = 0; i <= 20; i += 2) {
            System.out.print(i + " ");
        }
        System.out.println();

        // Multiplication table for 2
        int dan = 2;
        for (int i = 1; i <= 9; i++) {
            System.out.println(dan + " x " + i + " = " + (dan * i));
        }
    }
}

while and do-while

Used for condition-based repetition. do-while always executes at least once.

public class WhileExample {
    public static void main(String[] args) {
        // while: checks condition first
        int sum = 0;
        int num = 1;
        while (num <= 100) {
            sum += num;
            num++;
        }
        System.out.println("Sum of 1-100: " + sum); // 5050

        // do-while: executes at least once, then checks condition
        int count = 0;
        do {
            System.out.println("Execution count: " + (count + 1));
            count++;
        } while (count < 3);

        // Infinite loop (intentional use)
        int attempt = 0;
        while (true) {
            attempt++;
            System.out.println("Attempt " + attempt);
            if (attempt >= 5) {
                System.out.println("Max attempts reached, exiting!");
                break;
            }
        }
    }
}

Nested Loops

You can place a loop inside another loop to create 2D patterns.

public class NestedLoop {
    public static void main(String[] args) {
        // Full multiplication table
        for (int dan = 2; dan <= 9; dan++) {
            System.out.println("=== " + dan + " times table ===");
            for (int i = 1; i <= 9; i++) {
                System.out.println(dan + " x " + i + " = " + (dan * i));
            }
            System.out.println();
        }

        // Star triangle pattern
        int rows = 5;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        // *
        // * *
        // * * *
        // * * * *
        // * * * * *
    }
}

break and continue

Keywords that control the flow of loops.

public class BreakContinue {
    public static void main(String[] args) {
        // break: exit the loop immediately
        for (int i = 1; i <= 10; i++) {
            if (i == 6) {
                System.out.println("Stopped at 6!");
                break;
            }
            System.out.print(i + " "); // 1 2 3 4 5
        }
        System.out.println();

        // continue: skip the current iteration
        for (int i = 1; i <= 10; i++) {
            if (i % 3 == 0) {
                continue; // Skip multiples of 3
            }
            System.out.print(i + " "); // 1 2 4 5 7 8 10
        }
        System.out.println();

        // Using labels to break out of nested loops
        outer:
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                if (i * j > 10) {
                    System.out.println("Breaking at i=" + i + ", j=" + j);
                    break outer;
                }
                System.out.print(i * j + " ");
            }
            System.out.println();
        }
    }
}

Today’s Exercises

  1. Prime Number Finder: Write a program that prints only prime numbers from 2 to 100. Use nested for loops and break.

  2. Inverted Triangle Star Pattern: Print an inverted triangle star pattern with a height of 5 (5 stars on the first line, 1 star on the last line).

  3. Number Guessing Simulation: Set a target number (e.g., 42) in advance, and write a program that searches from 1 to 100, incrementing by 1, to find the answer. When found, print the number of attempts and exit the loop.

Was this article helpful?